Fabric Client 做為客戶端,連結節點的智能合約 - 鏈碼(chaincode),目前功能較完整的有 Node.js SDK。
Fabric-ca 是 Fabric 內建的 ca 服務,提供有以下 API,可取得 E-Cert、T-Cert 等。
客戶端(Client)程式構成如下:
Gateway(RESTful API)
初始化
//建立chaincode實體
chain = hfc.newChain("mychain");
//設定key pair儲存位置
chain.setKeyValStore(hfc.newFileKeyValStore(StorePath));
//設定hfc連線,使用grpc通訊協定
chain.setMemberServicesUrl("grpc://" + memberAddress);
chain.addPeer("grpc://" + peerAddress);
//設定為開發模式
chain.setDevMode(true);
//設定deploy返回時間
chain.setDeployWaitTime(3);
//設定交易返回時間
chain.setInvokeWaitTime(3);
使用者
//Enroll
chain.enroll
(
'admin'
, 'Xurw3yU9zI0l'
, function(err, admin)
{
if (err)
{
console.log("admin註冊失敗:%s", err);
process.exit(1);
}
chain.setRegistrar(admin);
blockChainUser = admin;
}
);
//Account
var request =
{
enrollmentID: 'ID',
affiliation: “Bank",
attributes:
[
{
name: 'name'
,value: 'Name'
}
,{
name: 'position',
value: 'Position'
}
]
};
//register
chain.register(request, function (err, user1)
{
if (err)
{
console.log(err);
}
blockChainUser = user1
//CallBack()
})
//registerAndEnroll
chain.registerAndEnroll(request, function (err, user1)
{
if (err)
{
console.log(err);
}
blockChainUser = user1
//CallBack()
})
鏈碼(Chaincode)呼叫
//Init
func (t *Handler) Init(stub shim.ChaincodeStubInterface) peer.Response {
}
//Invoke
func (t *Handler) Invoke(stub shim.ChaincodeStubInterface) peer.Response {
}
//Query
func (t *Handler) Query(stub shim.ChaincodeStubInterface, args []string) peer.Response {
}
enroll
app.post('/enroll', function(req, res)
{
var enrollID = req.body.enrollID;
var enrollSecret = req.body.enrollSecret;
userEnroll(enrollID, enrollSecret, function(result)
{
res.send(result);
})
})
deploy
app.post('/deploy', function(req, res)
{
var args = req.body.args;
var deployRequest =
{
chaincodeName: chaincodeName,
args: args,
fcn: "init"
}
if (blockChainUser != null)
{
var tx = blockChainUser.deploy(deployRequest);
}
}
tx.on('complete', function(results)
{
chainCodeID = results.chaincodeID;
res.send('ChainCodeID:' + chainCodeID);
});
tx.on('error', function(error)
{
res.send('Deploy失敗:' + error);
});
invoke
app.post('/invoke', function(req, res)
{
var args = req.body.args;
var invokeRequest =
{
chaincodeID: chainCodeID,
fcn: "invoke",
args: args
};
var tx = blockChainUser.invoke(invokeRequest);
}
tx.on('complete', function(results)
{
res.send('交易結果:' + JSON.stringify(results));
});
tx.on('error', function(error)
{
res.send('交易失敗:' + error);
})
query
app.post('/query', function(req, res)
{
var args = req.body.args;
var queryRequest =
{
chaincodeID: chainCodeID,
args: args,
fcn: "query"
}
var tx = blockChainUser.query(queryRequest);
}
tx.on('complete', function(results)
{
var result = new Buffer(results.result, 'hex').toString()
res.send('返回結果:' + result);
});
tx.on('error', function(error)
{
res.send('查詢失敗:' + error);
})
ajax
function postToServer(args, url)
{
$.post(url,
{
args: args
}
,function(data, state)
{
alert(data);
})
}